package com.xipu.yygh.listener;

import com.rabbitmq.client.Channel;
import com.xipu.yygh.manage.service.ScheduleService;
import com.xipu.yygh.model.hosp.Schedule;
import com.xipu.yygh.rabbit.constant.MqConst;
import com.xipu.yygh.rabbit.service.RabbitService;
import com.xipu.yygh.vo.msm.MsmVo;
import com.xipu.yygh.vo.order.OrderMqVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * description: 监听器
 * @author: gql
 * @date: 2022/05
 */
@Component
public class HospListener {
    /**
     * 排班信息(Mongo)
     */
    @Autowired
    private ScheduleService scheduleService;

    /**
     * RabbitMQ发送消息
     */
    @Autowired
    private RabbitService rabbitService;


    /**
     * 收到消息后减库存
     * @param orderMqVo 订单实体VO
     * @param message 消息对象
     * @param channel 信道
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void subtractCount(OrderMqVo orderMqVo, Message message, Channel channel) {
        // 1.查询出排班信息
        Schedule schedule = scheduleService.getByScheduleId(orderMqVo.getScheduleId());

        // 2.如果不包含剩余可约数,执行取消预约流程;如果包含剩余可以约数量,执行挂号流程
        if (ObjectUtils.isEmpty(orderMqVo.getAvailableNumber())) {
            // 更新剩余预约数
            schedule.setAvailableNumber(schedule.getAvailableNumber() + 1);
            this.scheduleService.updateSchedule(schedule);
        } else {
            // 设置可预约数、剩余预约数
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            // 调用方法更新
            this.scheduleService.updateSchedule(schedule);
        }

        // 3.向短信模块发送消息,让其发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (!ObjectUtils.isEmpty(msmVo)) {
            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}
